import random
import time

from sqlalchemy import and_

from exts import db
from flask import Blueprint, request, Response, jsonify, render_template, url_for, redirect, session
import json

from task.model import Task
from student.model import Student
from user.model import User

task = Blueprint('task', __name__);

# 任务列表
@task.route('task_list', methods=['GET', 'POST'])
def task_list():
    task_list = Task.query.all()
    return render_template('task_list.html', task_list=task_list)

# 负责人 搜索
@task.route('/task/search', methods=['GET', 'POST'])
def search():
    keyword = request.args.get('keyword')
    task_list = Task.query.filter(
        Task.name.like('%{keyword}%'.format(keyword=keyword))
    ).all()
    return render_template('task_list.html', task_list=task_list)

# 删除任务信息
@task.route('/task/remove', methods=['GET', 'POST'])
def remove():
    id = request.args.get('id')
    task = Task.query.filter(
        Task.id == id
    ).first()
    db.session.delete(task)
    db.session.commit()
    return redirect(url_for('task.task_list'))

# 任务信息 详情，编辑，更新，添加
@task.route('/task/edit', methods=['GET', 'POST'])
def edit():
    if request.method=='GET':
        id = request.args.get('id')
        option = request.args.get('option')
        task = Task.query.filter(
            Task.id == id
        ).first()
        if option == 'detail':
            return render_template('task_editor.html', task=task) 
        else:
            return render_template('task_editor.html', task=task, update=True)
    else:
        id = request.form.get('id')
        taskname = request.form.get('taskname')
        name = request.form.get('name')
        position = request.form.get('position')
        content = request.form.get('content')

        task = Task.query.filter(
            Task.id == id
        ).first()
        if task is None:
            task = Task(taskname=taskname, name=name, position=position,content=content)
            db.session.add(task)
            db.session.commit()
        else:
            task.taskname = taskname
            task.name = name
            task.position = position
            task.content = content
            db.session.commit()
        return redirect(url_for("task.task_list"))